package com.ruoyi.audit.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.domain.InventoryAmount;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyInvoice;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.mapper.ExpreeDeliveryMapper;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.mateProcurement.domain.MateOutbound;
import com.ruoyi.mateProcurement.domain.MateProcurement;
import com.ruoyi.mateProcurement.domain.MateProcurementModel;
import com.ruoyi.mateProcurement.service.MateOutboundService;
import com.ruoyi.mateProcurement.service.MateProcurementService;
import com.ruoyi.mateWarehousing.domain.MateWarehousing;
import com.ruoyi.monthlyInventory.domain.MonthlyInventory;
import com.ruoyi.monthlyInventory.domain.MonthlyInventoryLog;
import com.ruoyi.monthlyInventory.service.MonthlyInventoryService;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnModel;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnOrder;
import com.ruoyi.purchaseReturn.service.IPurchaseReturnService;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.saleReturn.domain.SaleReturnModel;
import com.ruoyi.saleReturn.domain.SaleReturnOrder;
import com.ruoyi.saleReturn.service.ISaleReturnService;
import com.ruoyi.salesInvoice.domain.SalesInvoiceOrder;
import com.ruoyi.salesInvoice.service.SalesInvoiceService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.service.WarehousingService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单审核Controller
 *
 * @author zjh
 * @date 2022-04-25
 */
@RestController
@RequestMapping("/audit")
public class AuditController extends BaseController {
    @Autowired
    ExpressDeliveryService expressDeliveryService;

    @Autowired
    ExpreeDeliveryMapper expreeDeliveryMapper;

    @Autowired
    SaleGoodsMapper saleGoodsMapper;

    @Autowired
    CompanyMapper companyMapper;
    private String prefix = "audit";

    @Autowired
    private AuditService auditService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private ICompanyInvoiceService invoiceService;

    @Autowired
    private SalesInvoiceService salesInvoiceService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISaleorderService iSaleorderService;

    @Autowired
    private ProcurementServer procurementServer;

    @Autowired
    private ISaleGoodsService iSaleGoodsService;

    @Autowired
    private MonthlyInventoryService monthlyInventoryService;

    @Autowired
    private WarehousingService warehousingService;

    @Autowired
    private IPurchaseReturnService iPurchaseReturnService;

    @Autowired
    private ISaleReturnService iSaleReturnService;

    @Autowired
    private ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private MateProcurementService mateProcurementService;

    @Autowired
    private MateOutboundService mateOutboundService;

    @RequiresPermissions("business:audit:view")
    @GetMapping()
    public String audit() {
        return prefix + "/audit";
    }

    @PostMapping("/selectInformation")
    @ResponseBody
    public Map<String, Object> selectInformation(HttpServletRequest request) {

        Map<String, Object> resMap = new HashMap<>();
        String saleordernum = request.getParameter("saleorderNum");
        String a = saleGoodsMapper.selectsalenuma(saleordernum);
        List<ExpressDelivery> list = new ArrayList<>();

        try {
            list = expressDeliveryService.selectInformation(a);
            if (list.size() == 0) {
                resMap.put("code", "-1");

            } else {
                resMap.put("code", "0");
                resMap.put("result", list);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;

    }

    @PostMapping("/selectOrderid")
    @ResponseBody
    public Map<String, Object> selectOrderid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        String saleordernum = httpServletRequest.getParameter("saleordernum");
        List<SaleGoodsOrder> list = saleGoodsMapper.selectorderid(saleordernum);
        if (list.size() == 0) {
            resMap.put("code", "-1");
        } else {
            resMap.put("code", "0");
            resMap.put("result", list);
        }
        return resMap;
    }

    @PostMapping("/selectInformationa")
    @ResponseBody
    public List<ExpressDelivery> selectInformationa(HttpServletRequest request) {
        String saleordernum = request.getParameter("saleorderNum");
        List<ExpressDelivery> list = new ArrayList<>();
        try {
            list = expressDeliveryService.selectInformation(saleordernum);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


    @PostMapping("/getname")
    @ResponseBody
    public List<SysUser> getname(HttpServletRequest request) {
        String userid = request.getParameter("userid");
        List<SysUser> list = new ArrayList<>();
        try {
            list = iSysUserService.getname(userid);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }

    @PostMapping("/getComPany")
    @ResponseBody
    public List<Company> getComPany() {

        List<Company> list = new ArrayList<>();
        try {
            String loginName = ShiroUtils.getLoginName();
            list = companyMapper.selectFhdz(loginName);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }


    @PostMapping("/placeOrder")
    @ResponseBody
    public Map<String, Object> placeOrder(@RequestBody JSONObject result) throws Exception {
        String saleorderNum = result.getString("saleorderNum");
        String msgData = result.getString("msgData");
        String recipients = result.getString("recipients");
        String sender = result.getString("sender");
        Map<String, Object> resMap = expressDeliveryService.placeOrder(msgData, saleorderNum, recipients, sender);
        return resMap;
    }

    @PostMapping("/placeOrder1")
    @ResponseBody
    public Map<String, Object> placeOrder1(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        String recipients = request.getParameter("recipients");//收件人电话号
        String sender = request.getParameter("sender");//寄件人手机号
        String msgData = request.getParameter("msgData1");
        String saleorderNum = request.getParameter("saleorderNum");
        Map<String, Object> resMap = expressDeliveryService.placeOrder(msgData, saleorderNum, recipients, sender);
        return resMap;
    }


    /**
     * 查询订单审核列表
     */
    @RequiresPermissions("business:audit:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "auditStatus", required = false) String auditStatus,
                              @RequestParam(value = "orderType", required = false) String orderType) {

        Audit audit = new Audit();
        startPage();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        audit.setCompanyId(companyId);
        audit.setAuditStatus(auditStatus);
        audit.setOrderType(orderType);
        List<Audit> list = auditService.selectAuditList(audit);
        for (Audit audit1 : list) {
            if (audit1.getMaterialName() != null) {
                audit1.setDeptName(audit1.getMaterialName());
            }
        }

        return getDataTable(list);
    }

   // @RequiresPermissions("business:audit:views")
    @GetMapping("/audits")
    public String audits() {
        return prefix + "/audits";
    }

    /**
     * 查询订单审核列表
     */
 //   @RequiresPermissions("business:audit:lists")
    @PostMapping("/lists")
    @ResponseBody
    public TableDataInfo lists(Audit audit) {
        startPage();
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        audit.setCompanyId(companyId);
        List<Audit> list = auditService.selectAuditLists(audit);
        return getDataTable(list);
    }

    /**
     * 导出订单审核列表
     */
    @RequiresPermissions("business:audit:export")
    @Log(title = "订单审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Audit audit) {
        List<Audit> list = auditService.selectAuditList(audit);
        ExcelUtil<Audit> util = new ExcelUtil<Audit>(Audit.class);
        return util.exportExcel(list, "订单审核数据");
    }

    /**
     * 新增订单审核
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存订单审核
     */
    @RequiresPermissions("business:audit:add")
    @Log(title = "订单审核", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Audit audit) {
        return toAjax(auditService.insertAudit(audit));
    }

    /**
     * 修改采购订单
     * 订单审核
     */
    @GetMapping("/selectEdit/{auditId}")
    @ResponseBody
    public Map<String, Object> edit(@PathVariable("auditId") Long auditId) {
        Map<String, Object> resMap = new HashMap<>();
        SysUser usera = SecurityUtils.getLoginUser().getUser();
        Audit audit = auditService.selectAuditById(auditId);
        resMap.put("auditId", auditId);
        resMap.put("auditStatus", audit.getAuditStatus());
        resMap.put("auditRemark", audit.getAuditRemark());
        String type = audit.getOrderType();
        if ("1".equals(type)) {
            Long purchaseId = audit.getOrderId();
            PurchaseOrder purchaseOrder = purchaseOrderService.selectPurchaseOrderById(purchaseId);
            List<PurchaseModel> purchaseModels = purchaseOrderService.selectPurchaseModelById(purchaseId);
            resMap.put("supplier", userService.selectSupplierById(usera.getCompanyId()));
            resMap.put("user", userService.selectSalesmanList(usera.getCompanyId()));
            Company company = companyMapper.selectByCompanyId(usera.getCompanyId());
            resMap.put("purchaseOrder", purchaseOrder);
            resMap.put("purchaseModels", purchaseModels);
            resMap.put("taxRate", company.getTaxRate());
//            JSONArray jsonArray = selectProduct(purchaseOrder.getSupplierId());
//            mmap.put("jsonArray", jsonArray);
            return resMap;
        } else if ("2".equals(type)) {
            //查看采购入库订单
            resMap.put("supplier", userService.selectSupplierById(usera.getCompanyId()));
            resMap.put("user", userService.selectSalesmanList(usera.getCompanyId()));
            ProcurementOrder procurementOrders = new ProcurementOrder();
            procurementOrders.setProcurementWarehousingId(audit.getOrderId());
            ProcurementOrder procurementOrder1 = procurementServer.selectProcurementBy(procurementOrders);
            List<ProcurementModel> procurementModels = procurementServer.selectProcurementModelById(audit.getOrderId());
            if (procurementServer.selectProcurementModelById(audit.getOrderId()).size() != 0) {
                resMap.put("procurementOrder", procurementOrder1);
            } else {
                procurementOrder1.setProcurementModelList(procurementModels);
                resMap.put("procurementOrder", procurementOrder1);
            }
            return resMap;
        } else if ("0".equals(type)) {
            Long saleorderId = audit.getOrderId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleorderId", saleorderId);
            //hashMap.put("deptId",ShiroUtils.getSysUser().getCompanyId());
            SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
            List<SaleorderModel> saleorderModelList = saleorderOrder.getSaleorderModels();
            for (SaleorderModel saleorderModel:saleorderModelList){
                if (saleorderModel.getUnit().equals("盒")){
                    saleorderModel.setRemainingNum(Math.toIntExact(saleorderModel.getRemainingNum() / saleorderModel.getFactor()));
                }

            }

            resMap.put("saleorderOrder", saleorderOrder);
//           SysUser sysUsers = iSysUserService.selectUserByDeptId(saleorderOrder.getCompanyId());
            SysUser sysUser = iSysUserService.selectUserById(saleorderOrder.getSaleorderUserId());
            Product product = new Product();
            product.setDeptId(usera.getCompanyId());
            Map<String, Object> map1 = new HashMap<>();
            map1.put("deptId", usera.getCompanyId());

            List<ProductModel> list = iSaleorderService.selectProductList(map1);
            if (saleorderOrder != null) {
                resMap.put("sysUsers", saleorderOrder.getDeptName());
            }
            if (sysUser != null) {
                resMap.put("user", sysUser);
            }
            if (list != null) {
                resMap.put("products", list);
            }
            String taxRate = saleorderOrder.getTaxRate();
            resMap.put("taxRate", taxRate);
            return resMap;
        } else if ("4".equals(type)) {
            MonthlyInventoryLog monthlyInventoryLog = monthlyInventoryService.selectMonthlyInventoryLogById(audit.getOrderId());
            MonthlyInventory monthlyInventory = monthlyInventoryService.selectMonthlyInventoryById(monthlyInventoryLog.getMonthlyInventoryId());
            resMap.put("monthlyInventory", monthlyInventory);
            resMap.put("num", monthlyInventoryLog.getChangeNum());
            return resMap;
        } else if ("5".equals(type)) {
            PurchaseReturnOrder purchaseReturnOrder = iPurchaseReturnService.selectPurchaseReturnById(audit.getOrderId());
            if (purchaseReturnOrder.getPurchaseReturnModels().get(0).getPurchaseReturnModelId() == null) {
                List<PurchaseReturnModel> list = new ArrayList();
                purchaseReturnOrder.setPurchaseReturnModels(list);
                resMap.put("purchaseReturnOrder", purchaseReturnOrder);
            } else {
                //查询 采购入库单的信息 set进model 中
                List<PurchaseReturnModel> purchaseReturnModels = purchaseReturnOrder.getPurchaseReturnModels();
                List<ProcurementModel> procurementModels = new ArrayList<>();
                for (int i = 0; i < purchaseReturnModels.size(); i++) {
                    Long procurementWarehousingNo = purchaseReturnModels.get(i).getProcurementWarehousingNo();
                    ProcurementModel procurementModel = iPurchaseReturnService.selectProcurementModelByNo(procurementWarehousingNo);
                    for (PurchaseReturnModel purchaseReturnModel : purchaseReturnModels) {
                        if (purchaseReturnModel.getUnit().equals("盒") || purchaseReturnModel.getUnit() == "盒") {
                            List<Integer> list1 = procurementServer.selectProductType(procurementModel.getProductType());
                            int a = list1.get(0);
                            if (a != 0) {
                                int alllnum = purchaseReturnModel.getAllNum();
                                Long b = Long.valueOf(a);
                                Long c = alllnum / b;
                                purchaseReturnModel.setAllNum(c.intValue());
                            }
                        }
                    }
                    purchaseReturnModels.get(i).setProcurementModel(procurementModel);
                    procurementModel.setReturnNum(purchaseReturnModels.get(i).getReturnNum());
                    procurementModel.setTaxTotal(purchaseReturnModels.get(i).getTaxTotal());
                    procurementModels.add(procurementModel);
                }
                resMap.put("purchaseReturnOrder", purchaseReturnOrder);
                resMap.put("procurementModels", procurementModels);
            }
            List<SysUser> sysUsers = iSysUserService.selectSupplierById(usera.getCompanyId());
            List<SysUser> user = iSysUserService.selectSalesmanList(usera.getCompanyId());
            Product product = new Product();
            product.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
            Map<String, Object> map1 = new HashMap<>();
            map1.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
            List<ProductModel> list = iSaleorderService.selectProductList(map1);
            CompanyInvoice companyInvoice = iCompanyInvoiceService.selectByCompanyId(usera.getCompanyId());
            if (sysUsers != null) {
                resMap.put("sysUsers", sysUsers);
            }
            if (user != null) {
                resMap.put("user", user);
            }
            if (list != null) {
                resMap.put("products", list);
            }
            if (companyInvoice != null) {
                resMap.put("taxRate", companyInvoice.getTaxRate());
            }
            //供应商
            Long procurementWarehousingId = purchaseReturnOrder.getProcurementWarehousingId();
            ProcurementOrder procurementOrder = procurementServer.selectProcurementById(procurementWarehousingId);
            Long supplierId = procurementOrder.getSupplierId();
            SysDept sysDept = iSysDeptService.selectDeptById(supplierId);
            String supplierName = null;
            if (sysDept != null) {
                supplierName = sysDept.getDeptName();
            }
            resMap.put("supplierName", supplierName);
            return resMap;
        } else if ("6".equals(type)) {
            List<SaleGoodsModel> saleGoodsModelList = new ArrayList<>();
            //查看销售退货单
            SaleReturnOrder saleReturnOrder = iSaleReturnService.selectSaleReturnOrderAndModelById(audit.getOrderId());
            if (saleReturnOrder.getSaleReturnModels().get(0).getSaleReturnId() == null) {
                List<SaleReturnModel> list = new ArrayList();
                saleReturnOrder.setSaleReturnModels(list);
                resMap.put("saleReturnOrder", saleReturnOrder);
            } else {
                //查询 采购入库单的信息 set进model 中
                List<SaleReturnModel> saleReturnModels = saleReturnOrder.getSaleReturnModels();
                List<ProcurementModel> procurementModels = new ArrayList<>();
                if (saleReturnOrder.getPurchaseReturnId() != null) {
                    for (int i = 0; i < saleReturnModels.size(); i++) {
                        SaleReturnModel saleReturnModel = saleReturnModels.get(i);
                        //采购入库从表 信息
                        PurchaseReturnModel purchaseReturnModel = iPurchaseReturnService.selectPurchaseReturnModelById(saleReturnModel.getPurchaseReturnModelId());
                        Long procurementWarehousingNo = purchaseReturnModel.getProcurementWarehousingNo();
                        ProcurementModel procurementModel = iPurchaseReturnService.selectProcurementModelByNo(procurementWarehousingNo);
                        procurementModel.setNum(procurementModel.getPurchaseNum());
                        procurementModel.setOutNum(purchaseReturnModel.getReturnNum());
                        procurementModels.add(procurementModel);
                        saleReturnModel.setProcurementModel(procurementModel);
                    }
                } else {
                    for (int i = 0; i < saleReturnModels.size(); i++) {
                        SaleReturnModel saleReturnModel = saleReturnModels.get(i);
                        SaleGoodsModel saleGoodsModel = iSaleGoodsService.selectSaleGoodsModelByModelId(saleReturnModel.getSaleGoodsModelId());
                        saleGoodsModel.setOutNum(saleReturnModel.getReturnNum());
                        saleGoodsModel.setRemainingNum(saleGoodsModel.getNum() - saleReturnModel.getReturnNum());
                        saleGoodsModel.setTaxTotal(saleReturnModel.getTaxTotal());
                        saleReturnModel.setSaleGoodsModel(saleGoodsModel);
                        saleGoodsModelList.add(saleGoodsModel);
                    }
                }
                if ("".equals(saleReturnOrder.getSaleGoodsNum())) {
                    saleReturnOrder.setSaleGoodsNum(null);
                }
                if ("".equals(saleReturnOrder.getProcurementWarehousingName())) {
                    saleReturnOrder.setProcurementWarehousingName(null);
                }
                resMap.put("saleReturnOrder", saleReturnOrder);
                resMap.put("saleGoodsModel", saleGoodsModelList);
                resMap.put("procurementModels", procurementModels);
            }
            List<SysUser> sysUsers = iSysUserService.selectSupplierById(usera.getCompanyId());
            List<SysUser> user = iSysUserService.selectSalesmanList(usera.getCompanyId());
            Product product = new Product();
            product.setDeptId(usera.getCompanyId());
            Map<String, Object> map1 = new HashMap<>();
            map1.put("deptId", usera.getCompanyId());
            List<ProductModel> list = iSaleorderService.selectProductList(map1);
            CompanyInvoice companyInvoice = iCompanyInvoiceService.selectByCompanyId(usera.getCompanyId());
            if (sysUsers != null) {
                resMap.put("sysUsers", sysUsers);
            }
            if (user != null) {
                resMap.put("user", user);
            }
            if (list != null) {
                resMap.put("products", list);
            }
            if (companyInvoice != null) {
                resMap.put("taxRate", companyInvoice.getTaxRate());
            }
            return resMap;
        } else if ("7".equals(type)) {
            //审核销售发票
            SalesInvoiceOrder salesInvoiceOrder = salesInvoiceService.selectSalesInvoiceOrderById(audit.getOrderId());
            Long companyId = usera.getCompanyId();
            Long deptId = usera.getDeptId();
            Long userId = usera.getUserId();
            List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
            //定义一个i，用于采购的业务员的判断
            int i = 0;
            if (!deptId.equals(companyId)) {
                if (sysUsers.size() != 0) {
                    for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                        if (!sysUsers.get(i1).getUserId().equals(userId)) {
                            sysUsers.remove(i1);
                            i++;
                        }
                    }
                }
            }
            resMap.put("user", sysUsers);
            resMap.put("salesInvoiceOrder", salesInvoiceOrder);
            return resMap;
        } else if ("8".equals(type)) {
            MateProcurement mateProcurement = mateProcurementService.selectMateProcurementByOrderId(audit.getOrderId());
            resMap.put("mateProcurement", mateProcurement);
            return resMap;
        } else if ("9".equals(type)) {
            MateOutbound mateOutbound1 = new MateOutbound();
            mateOutbound1.setMateGoodsId(audit.getOrderId());
            MateOutbound mateOutbound = mateOutboundService.selectMateOutboundBy(mateOutbound1);
            resMap.put("mateOutbound", mateOutbound);
            return resMap;
        } else {
            //审核销货单
            //将销货单选择的销售订单 状态改为已出库
            //获取销货单id
            Long saleGoodsId = audit.getOrderId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleGoodsId", saleGoodsId);
            hashMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
            SaleGoodsOrder saleGoodsOrder = iSaleGoodsService.selectSaleGoodsById(hashMap);
            //判断子集是否存在
            if (saleGoodsOrder.getSaleGoodsModels().get(0).getSaleGoodsModelId() == null) {
                //没有的话 给个空的集合
                List<SaleGoodsModel> list = new ArrayList();
                saleGoodsOrder.setSaleGoodsModels(list);
                resMap.put("saleGoodsOrder", saleGoodsOrder);
            } else {
                List<SaleGoodsModel> list = saleGoodsOrder.getSaleGoodsModels();
                for (SaleGoodsModel saleGoodsModel : list) {
                    if (saleGoodsModel.getUnit().equals("盒") || saleGoodsModel.getUnit() == "盒") {
                        saleGoodsModel.setAmount(saleGoodsModel.getAmount() / saleGoodsModel.getFactor().intValue());
                    }
                }
                resMap.put("saleGoodsOrder", saleGoodsOrder);
            }
            List<SysUser> sysUsers = iSysUserService.selectSupplierById(usera.getCompanyId());
            List<SysUser> user = iSysUserService.selectSalesmanList(usera.getCompanyId());
            Product product = new Product();
            product.setDeptId(usera.getCompanyId());
            Map<String, Object> map1 = new HashMap<>();
            map1.put("deptId", usera.getCompanyId());
            if (sysUsers != null) {
                resMap.put("sysUsers", sysUsers);
            }
            if (user != null) {
                resMap.put("user", user);
            }
            String taxRate = saleGoodsOrder.getTaxRate();
            resMap.put("taxRate", taxRate);
            return resMap;
        }
    }

    @Log(title = "查询供应商下的所有产品", businessType = BusinessType.DELETE)
    @PostMapping("/selectProduct/{deptId}")
    @ResponseBody
    public JSONArray selectProduct(@PathVariable("deptId") Long deptId) {
        List<Product> productList = purchaseOrderService.selectProduct(deptId);
        JSONArray array = new JSONArray();
        for (Product product : productList) {
            if (product.getProductModel().size() != 0) {
                List<ProductModel> productModels = product.getProductModel();
                for (ProductModel productModel : productModels) {
                    JSONObject obj = new JSONObject();
                    obj.put("productId", product.getProductId());
                    obj.put("productName", product.getProductName());
                    obj.put("modelNo", productModel.getModelNo());
                    obj.put("modelCode", productModel.getModelCode());
                    obj.put("productType", productModel.getProductType());
                    obj.put("warehousingNum", productModel.getWarehousingNum());
                    obj.put("salesUnit", productModel.getSalesUnit());
                    array.add(obj);
                }
            }
        }
        return array;
    }

    @PostMapping("/selectProductType")
    @ResponseBody
    public List<Integer> selectProductType(HttpServletRequest request) {
        String productType = request.getParameter("productType");
        return procurementServer.selectProductType(productType);
    }

    @PostMapping("/updateSaleOrderModel")
    @ResponseBody
    public Map<String, Object> updateSaleOrderModel(@RequestBody JSONObject saleGoodsModels) {
        int i = 0;
        JSONArray aa = saleGoodsModels.getJSONArray("saleGoodsModels");
        List<SaleGoodsModel> saleGoodsModels1 = aa.toJavaList(SaleGoodsModel.class);
        Map<String, Object> resMap = new HashMap<>();
        for (SaleGoodsModel saleGoodsModel : saleGoodsModels1) {
            List<SaleorderModel> list = saleGoodsMapper.selectNum(saleGoodsModel);
            for (SaleorderModel saleorderModel : list) {
                if (saleGoodsModel.getSaleorderModelId().equals(saleorderModel.getSaleorderModelId())) {
                    saleorderModel.setExecuteNum(saleGoodsModel.getAllNum() + saleorderModel.getExecuteNum());
                    saleorderModel.setRemainingNum(saleorderModel.getRemainingNum() - saleGoodsModel.getAllNum());
                    saleorderModel.setAllNum(saleorderModel.getAllNum() - saleGoodsModel.getAllNum());
                    i = saleGoodsMapper.updateSaleOrderModel(saleorderModel);
                }
            }
        }
        if (i >= 1) {
            resMap.put("code", 200);

        } else {
            resMap.put("code", -1);
        }
        return resMap;
    }

    /**
     * 修改保存订单审核
     */
    @RequiresPermissions("business:audit:edit")
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "订单审核", businessType = BusinessType.UPDATE)
    @GetMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(value = "auditId", required = false) Long auditId, @RequestParam(value = "auditStatus", required = false) String auditStatus) {
        Audit audit = new Audit();
        audit.setAuditId(auditId);
        audit.setAuditStatus(auditStatus);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Audit audit1 = auditService.selectAuditByIdIn(audit.getAuditId());
        if (audit1.getAuditStatus().equals("1") || audit1.getAuditStatus().equals("2")) {
            audit.setAuditStatus(audit1.getAuditStatus());
            return AjaxResult.error("该订单已经审核完成");
        }
        if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
            audit1.setAuditBy(sysUser.getNickName());
            audit1.setAuditTime(DateUtils.getNowDate());
        }
        if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
            audit.setAuditBy(sysUser.getNickName());
            audit.setAuditTime(DateUtils.getNowDate());
        }
        Long deptId = sysUser.getCompanyId();
        int i = auditService.updateAudit(audit, deptId);
        InventoryAmount inventoryAmount = new InventoryAmount();
        if ("2".equals(audit1.getOrderType()) && i == 1) {
            //采购入库
            ProcurementOrder procurementOrder = new ProcurementOrder();
            procurementOrder.setProcurementWarehousingId(audit1.getOrderId());
            if (audit.getAuditStatus().equals("1")) {
                procurementServer.calculation(procurementOrder);
                inventoryAmount.setDeptId(sysUser.getCompanyId());
                inventoryAmount.setOrderType("0");
                inventoryAmount.setOrderId(audit1.getOrderId());
                inventoryAmount.setAuditId(audit1.getAuditId());
                auditService.insertInventoryAmount(inventoryAmount);
            }

        } else if ("3".equals(audit1.getOrderType())) {
            //销货单
            SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
            saleGoodsOrder.setSaleGoodsId(audit1.getOrderId());
            saleGoodsOrder.setSaleGoodsStatus(audit.getAuditStatus());
            if (audit.getAuditStatus().equals("1")) {
                iSaleGoodsService.outboundAudit(saleGoodsOrder);
                inventoryAmount.setDeptId(sysUser.getCompanyId());
                inventoryAmount.setOrderType("1");
                inventoryAmount.setOrderId(audit1.getOrderId());
                inventoryAmount.setAuditId(audit1.getAuditId());
                auditService.updateInventoryAmount(inventoryAmount);
            } else {
                iSaleGoodsService.auditSalesOrderEdit(audit1.getOrderId());
            }
        } else if ("4".equals(audit1.getOrderType()) && audit.getAuditStatus().equals("1")) {
            MonthlyInventoryLog monthlyInventoryLog = new MonthlyInventoryLog();
            monthlyInventoryLog.setLogId(audit1.getOrderId());
            warehousingService.calculation(monthlyInventoryLog);
        } else if ("5".equals(audit1.getOrderType())) {
            //采购退货
            PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
            purchaseReturnOrder.setPurchaseReturnId(audit1.getOrderId());
            purchaseReturnOrder.setPurchaseReturnStatus(audit.getAuditStatus());
            iPurchaseReturnService.returnAudit(purchaseReturnOrder);
        } else if ("6".equals(audit1.getOrderType())) {
            //销售退货
            Long saleReturnId = audit1.getOrderId();
            String status = audit.getAuditStatus();
            iSaleReturnService.saleReturnAudit(saleReturnId, status);
        } else if ("7".equals(audit1.getOrderType())) {
            Long salesInvoiceId = audit1.getOrderId();
            String status = audit.getAuditStatus();
            if (status.equals("2")) {
                salesInvoiceService.countReturnSalesGoods(salesInvoiceId);
            } else {
                salesInvoiceService.countIsInvoice(salesInvoiceId);
            }
        } else if ("8".equals(audit1.getOrderType())) {
            MateProcurement mateProcurement = new MateProcurement();
            Long mateProcurementId = audit1.getOrderId();
            mateProcurement.setMateProcurementId(mateProcurementId);
            if (audit.getAuditStatus().equals("1")) {
                mateProcurementService.caculation(mateProcurement);
            }
        } else if ("9".equals(audit1.getOrderType())) {
            MateOutbound mateOutbound = new MateOutbound();
            Long mateGoodsId = audit1.getOrderId();
            mateOutbound.setMateGoodsId(mateGoodsId);
            if (audit.getAuditStatus().equals("1")) {
                mateOutboundService.caculation(mateOutbound);
            }
        }
        return toAjax(i);
    }

    /**
     * 删除订单审核
     */
    @RequiresPermissions("business:audit:remove")
    @Log(title = "订单审核", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(auditService.deleteAuditByIds(ids));
    }

    /**
     * 确认审批退回
     */
    @Transactional
    @GetMapping("/returnReview/{auditId}")
    @ResponseBody
    public int returnReview(@PathVariable("auditId") Long auditId) {
        Audit audit1 = auditService.selectAuditByIdIn(auditId);
        if (audit1.getAuditStatus().equals("0")) {
            return 2;
        }
        int i = auditService.returnReview(auditId);
        if (i != 0) {
            return 1;
        } else {
            return 2;
        }
    }

}